import React, { Component } from 'react'

import { inject, observer } from 'mobx-react/native'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import moment from 'moment'
import { Carousel, Modal, Toast, WhiteSpace } from 'antd-mobile'
import {
  Button,
  Dimensions,
  Image,
  ScrollView,
  StyleSheet,
  View,
} from 'react-native'

import { IconButton, Entity, WhiteButton } from '../components'
import client from '../client'
import store from '../store'

const QUERY_ITEM = gql`
  query($id: ID!) {
    Item(id: $id) {
      id
      title
      intro
      price
      category {
        id
        title
      }
      tags
      images
      createdAt
      updatedAt
    }
  }
`

@graphql(QUERY_ITEM, {
  options: ({ navigation }) => ({
    variables: { id: navigation.getParam('id') },
  }),
})
export class ItemScreen extends Component {
  get data() {
    const key = 'Item'
    const loaded = this.props.data && !this.props.data.loading
    const data = loaded ? this.props.data[key] : {}
    return {
      ...data,
      images: data.images || [
        'https://zos.alipayobjects.com/rmsportal/TekJlZRVCjLFexlOCuWn.png',
        'https://zos.alipayobjects.com/rmsportal/AiyWuByWklrrUDlFignR.png',
        'https://zos.alipayobjects.com/rmsportal/IJOtIlfsYdTyaDTRVrLI.png',
      ],
    }
  }

  render = () => (
    <ScrollView style={styles.container}>
      <Carousel infinite>
        {this.data.images.map(uri => (
          <Image
            key={uri}
            style={{ width: Dimensions.get('window').width, height: 200 }}
            source={{ uri }}
          />
        ))}
      </Carousel>
      <Entity
        data={this.data}
        loading={this.props.data.loading}
        schema={[
          { key: 'title', label: 'Title', wrap: true },
          { key: 'intro', label: 'Intro', wrap: true },
          {
            key: 'price',
            label: 'Price',
            render: price => (price / 100).toFixed(2),
          },
          {},
          { key: 'category.title', label: 'Category' },
          {
            key: 'tags',
            label: 'Tags',
            render: tags => tags.join(', '),
          },
          {},
          {
            key: 'updatedAt',
            label: 'Update Time',
            render: time => moment(time).calendar(),
          },
        ]}
      />
      <WhiteSpace />
      <WhiteButton
        title="Add to Cart"
        onPress={() => {
          store.actions.addToCart(this.data, 1)
          Toast.success('Success', 1, undefined, false)
        }}
      />
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
})
